package cdbft

import (
	"blockchain/public/function"
	"crypto/sha256"
	"encoding/json"
)

func replyDelegate(nodeSeq int){
	replyDataDelegate(nodeSeq)
	var reply replyMessage
	reply.nodeSeq=nodeSeq
	reply.trades=tradeSet[nodeSeq]
	data,_:=json.Marshal(reply.trades)
	reply.sign=function.Sign(data,nodeSeq)
	var flagReplied =make(chan bool)
	go nodeSendReplyMessageDelegate(nodeSeq,flagReplied,reply)
	<-flagReplied
}

func nodeSendReplyMessageDelegate(nodeSeq int,flagReplied chan bool,reply replyMessage){
	select {
	case chanRecReply<-reply:
		FlagReplied[nodeSeq]<-true
		close(FlagReplied[nodeSeq])
	default:FlagReplied[nodeSeq]<-false
		close(FlagReplied[nodeSeq])
	}
	flagReplied<-true
	close(flagReplied)
}

func replyDataDelegate(nodeSeq int){
	dat,_:=json.Marshal(tradeSet[nodeSeq])
	hash:=sha256.Sum256(dat)
	var commit [2*groupNum+1]commitMessage
	count:=0
	for data:=range chanRecCommit[nodeSeq]{
		res:=function.VerifySignHash(data.tradeHash,data.sign,data.nodeSeq)
		if res{
			commit[count]=data
			count++
		}
	}
	//println(count)
	count=0
	for i:=0;i<2*groupNum/3+1;i++{
		if commit[i].tradeHash==hash{
			count++
		}
	}
	if count>groupNum/3{
		for i:=0;i<TradeSize;i++{
			tradeSet[nodeSeq][i].Result=tradeSet[nodeSeq][i].Remainder-tradeSet[nodeSeq][i].Send
		}
	}
}